﻿using System;
using System.Web;
using System.Collections;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using System.Configuration;
using Microsoft.VisualBasic;
using System.Text;
using System.Net;
using System.IO;

namespace AspDIY.Net.Common
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// 程序版本
        /// </summary>
        public const string Assembly_Version = "2.0.0";

        private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);

        /// <summary>
        /// AppSettings集合
        /// </summary>
        public static System.Collections.Specialized.NameValueCollection AppSettings = ConfigurationManager.AppSettings;

        #region 弹出Alert窗口(静态)
        /// <summary>
        /// 弹出Alert窗口(静态)
        /// </summary>
        /// <param name="Str">字符串</param>
        /// <param name="Url">转向地址</param>
        /// <param name="Style">输入样式 0只弹出 1弹出并在当前窗口转向 2弹出并在顶级窗口转向 3弹出并自定义操作 4直接转向 默认只弹出</param>
        /// <returns>字符串</returns>
        public static string Alert(string Str, string Url, int Style)
        {
            //输出提示信息
            switch (Style)
            {
                case 0:
                    return "<script langue=javascript>alert('" + Str + "')</script>";
                case 1:
                    return "<script langue=javascript>alert('" + Str + "');window.location=\"" + Url + "\";</script>";
                case 2:
                    return "<script langue=javascript>alert('" + Str + "');top.location=\"" + Url + "\";</script>";
                case 3:
                    return "<script langue=javascript>alert('" + Str + "');" + Url + ";</script>";
                case 4:
                    return "<script langue=javascript>window.location=\"" + Url + "\";</script>";
                default:
                    return "<script langue=javascript>alert('" + Str + "')</script>";
            }
        }

        #endregion


        #region 文件操作

        #region 判断文件是否存在
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="FilePath">绝对路径</param>
        /// <returns>true或false</returns>
        public static bool FileExists(string FilePath)
        {
            if (File.Exists(FilePath))
                return true;
            else
                return false;
        }
        #endregion

        #region 写文件
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="FilePath">绝对路径+文件名</param>
        /// <param name="strValue">字符串</param>
        /// <param name="encoder">编码 utf8 gb2312</param>
        /// <returns>true或false</returns>
        public static bool FileWrite(string FilePath, string strValue, string encoder)
        {
            if (FileExists(FilePath)) File.Delete(FilePath);

            StreamWriter f = new StreamWriter(FilePath, true, Encoding.GetEncoding(encoder));
            f.WriteLine(strValue);
            f.Close();
            f.Dispose();
            return FileExists(FilePath);
        }
        #endregion

        #region 读文件
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="FilePath">绝对路径+文件名</param>
        /// <param name="encoder">编码 utf8 gb2312</param>
        /// <returns>字符串</returns>
        public static string FileRead(string FilePath, string encoder)
        {
            string s = "";
            if (FileExists(FilePath))
            {
                StreamReader f = new StreamReader(FilePath, System.Text.Encoding.GetEncoding(encoder));
                s = f.ReadToEnd();
                f.Close();
                f.Dispose();
            }

            return s;
        }
        #endregion

        #region 追加文件
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="FilePath">绝对路径+文件名</param>
        /// <param name="strValue">字符串</param>
        /// <returns>true或false</returns>
        public static bool FileAdd(string FilePath, string strValue)
        {
            if (FileExists(FilePath))
            {
                StreamWriter sw = File.AppendText(FilePath);
                sw.Write(strValue);
                sw.Flush();
                sw.Close();
                sw.Dispose();
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 拷贝文件
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="sourceFile">绝对路径+文件名</param>
        /// <param name="destFile">绝对路径+新文件名</param>
        /// <returns>true或false</returns>
        public static bool FileCoppy(string sourceFile, string destFile)
        {
            if (FileExists(sourceFile))
            {
                File.Copy(sourceFile, destFile, true);
                return FileExists(destFile);
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 移动文件
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourceFile">绝对路径+文件名</param>
        /// <param name="destFile">绝对路径+新文件名</param>
        /// <returns>true或false</returns>
        public static bool FileMove(string sourceFile, string destFile)
        {
            if (FileExists(sourceFile))
            {
                File.Move(sourceFile, destFile);
                return FileExists(destFile);
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FilePath">绝对路径+文件名</param>
        /// <returns>true或false</returns>
        public static bool FileDel(string FilePath)
        {
            File.Delete(FilePath);
            return !FileExists(FilePath);
        }
        #endregion

        #region 判断目录是否存在
        /// <summary>
        /// 判断目录是否存在
        /// </summary>
        /// <param name="Path">绝对路径</param>
        /// <returns>true或false</returns>
        public static bool FolderExists(string Path)
        {
            if (Directory.Exists(Path))
                return true;
            else
                return false;
        }
        #endregion

        #region 创建目录
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="Path">绝对路径</param>
        /// <returns>true或false</returns>
        public static bool FolderCreate(string Path)
        {
            // 判断目标目录是否存在如果不存在则新建之
            if (!FolderExists(Path))
                Directory.CreateDirectory(Path);
            return FolderExists(Path);
        }
        #endregion

        #region 递归删除文件夹目录及文件
        /// <summary>
        /// 递归删除文件夹目录及文件
        /// </summary>
        /// <param name="Path">绝对路径</param>
        /// <returns>true或false</returns>
        public static bool FolderDelete(string Path)
        {
            if (FolderExists(Path)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(Path))
                {
                    if (FileExists(d))
                        File.Delete(d); //直接删除其中的文件                        
                    else
                        FolderDelete(d); //递归删除子文件夹 
                }
                Directory.Delete(Path, true); //删除已空文件夹                 
            }
            return FolderExists(Path);
        }
        #endregion

        #region 将指定文件夹下面的所有内容copy到目标文件夹下面。
        /// <summary>
        /// 将指定文件夹下面的所有内容copy到目标文件夹下面。
        /// </summary>
        /// <param name="sourcePath">绝对路径</param>
        /// <param name="destPath">新绝对路径</param>
        /// <returns>true或false</returns>
        public static bool FolderCopy(string sourcePath, string destPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (destPath[destPath.Length - 1] != Path.DirectorySeparatorChar)
                    destPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!FolderExists(destPath))
                    Directory.CreateDirectory(destPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(Olddir);
                string[] fileList = Directory.GetFileSystemEntries(sourcePath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (FolderExists(file))
                        FolderCopy(file, destPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, destPath + Path.GetFileName(file), true);
                }
                return FolderExists(destPath);
            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }
        #endregion

        #region 获取指定文件的扩展名
        /// <summary>
        /// 获取指定文件的扩展名
        /// </summary>
        /// <param name="fileName">指定文件名</param>
        /// <returns>扩展名</returns>
        public static string FileExtName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || fileName.IndexOf('.') <= 0)
                return "";

            fileName = fileName.ToLower().Trim();

            return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
        }
        #endregion

        #region 以指定的ContentType输出指定文件文件
        /// <summary>
        /// 以指定的ContentType输出指定文件文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="filename">输出的文件名</param>
        /// <param name="filetype">将文件输出时设置的ContentType</param>
        public static void ResponseFile(string filepath, string filename, string filetype)
        {
            Stream iStream = null;

            // 缓冲区为10k
            byte[] buffer = new Byte[10000];
            // 文件长度
            int length;
            // 需要读的数据长度
            long dataToRead;

            try
            {
                // 打开文件
                iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                // 需要读的数据长度
                dataToRead = iStream.Length;

                HttpContext.Current.Response.ContentType = filetype;
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename.Trim()).Replace("+", " "));

                while (dataToRead > 0)
                {
                    // 检查客户端是否还处于连接状态
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        // 如果不再连接则跳出死循环
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    // 关闭文件
                    iStream.Close();
                }
            }
            HttpContext.Current.Response.End();
        }
        #endregion

        #region 获得当前绝对路径
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string MapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        #endregion

        #region 根据Url获得源文件内容
        /// <summary>
        /// 根据Url获得源文件内容
        /// </summary>
        /// <param name="url">合法的Url地址</param>
        /// <returns></returns>
        public static string GetSourceTextByUrl(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 20000;//20秒超时
            WebResponse response = request.GetResponse();

            Stream resStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(resStream);
            return sr.ReadToEnd();
        }
        #endregion

        #endregion

        #region 字符串操作

        #region MD5 32位算法
        /// <summary>
        /// MD5 32位算法
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>MD5 32位算法后的字符串</returns>
        public static string ToMD5(string strValue)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strValue, "md5");
        }
        #endregion

        #region SHA1算法
        /// <summary>
        /// SHA1位算法
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>SHA1算法后的字符串</returns>
        public static string ToSHA1(string strValue)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strValue, "SHA1");
        }
        #endregion

        #region 编解码操作
        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string strValue)
        {
            return HttpUtility.HtmlEncode(strValue);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string strValue)
        {
            return HttpUtility.HtmlDecode(strValue);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string strValue)
        {
            return HttpUtility.UrlEncode(strValue);
        }

        /// <summary>
        /// 返回 URL 字符串的解码结果
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string strValue)
        {
            return HttpUtility.UrlDecode(strValue);
        }
        #endregion

        #region 输出字符串
        /// <summary>
        /// 输出内容
        /// </summary>
        /// <param name="strValue">内容</param>
        /// <returns></returns>
        public static void Write(string strValue)
        {
            Write(strValue, false);
        }
        /// <summary>
        /// 输出内容
        /// </summary>
        /// <param name="strValue">内容</param>
        /// <param name="IsEnd">是否输出后结束</param>
        /// <returns></returns>
        public static void Write(string strValue,bool IsEnd)
        {
            System.Web.HttpContext.Current.Response.Write(strValue);
            if (IsEnd) System.Web.HttpContext.Current.Response.End();
        }
        #endregion

        #region 将全角数字转换为数字
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase">全角数字</param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }
        #endregion

        #region 简繁体互转
        /// <summary>
        /// 转换为简体中文
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string ToSChinese(string strValue)
        {
            return Strings.StrConv(strValue, VbStrConv.SimplifiedChinese, 0);
        }

        /// <summary>
        /// 转换为繁体中文
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string ToTChinese(string strValue)
        {
            return Strings.StrConv(strValue, VbStrConv.TraditionalChinese, 0);
        }
        #endregion

        #region 中英文混排字符串截取
        /// <summary>
        /// 中英文混排字符串截取
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="Length">截取长度</param>
        /// <param name="TailString">用于替换的字符串</param>
        /// <returns>截取后字符串</returns>
        public static string SubString(string strValue, int Length, string TailString)
        {
            string result = string.Empty;// 最终返回的结果
            int byteLen = StringLength(strValue);// 单字节字符长度
            int charLen = strValue.Length;// 把字符平等对待时的字符串长度
            int byteCount = 0;// 记录读取进度
            int pos = 0;// 记录截取位置
            if (byteLen > Length)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(strValue.ToCharArray()[i]) > 255)// 按中文字符计算加2
                        byteCount += 2;
                    else// 按英文字符计算加1
                        byteCount += 1;
                    if (byteCount > Length)// 超出时只记下上一个有效位置
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == Length)// 记下当前位置
                    {
                        pos = i + 1;
                        break;
                    }
                }

                if (pos >= 0) result = strValue.Substring(0, pos);
                if (TailString != "") result += TailString;
            }
            else
                result = strValue;

            return result;
        }
        /// <summary>
        /// 中英文混排字符串长度
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>长度</returns>
        public static int StringLength(string strValue)
        {
            if (strValue != "") return System.Text.Encoding.Default.GetByteCount(strValue);// 单字节字符长度
            else return 0;
        }



        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串
        /// </summary>
        /// <param name="strValue">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string SubString(string strValue, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                        startIndex = startIndex - length;
                }

                if (startIndex > strValue.Length)
                    return "";
            }
            else
            {
                if (length < 0)
                    return "";
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                        return "";
                }
            }

            if (strValue.Length - startIndex < length)
                length = strValue.Length - startIndex;

            return strValue.Substring(startIndex, length);
        }

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="strValue">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string SubString(string strValue, int startIndex)
        {
            return SubString(strValue, startIndex, strValue.Length);
        }
        #endregion

        #region 字符中分割函数
        /// <summary>
        /// 字符中分割函数
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <returns>string[]数组</returns>
        public static string[] Split(string strValue, string strSplit)
        {
            string[] strtmp = new string[1];
            int index = strValue.IndexOf(strSplit, 0);
            if (index < 0)
            {
                strtmp[0] = strValue;
                return strtmp;
            }
            else
            {
                strtmp[0] = strValue.Substring(0, index);
                return Split(strValue.Substring(index + strSplit.Length), strSplit, strtmp);
            }
        }
        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="Count">并指定长度</param>
        /// <returns>string[]数组</returns>
        /// <returns></returns>
        public static string[] Split(string strValue, string strSplit, int Count)
        {
            string[] result = new string[Count];
            string[] splited = Split(strValue, strSplit);

            for (int i = 0; i < Count; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="ignoreRepeatItem">忽略重复项</param>
        /// <returns></returns>
        public static string[] Split(string strValue, string strSplit, bool ignoreRepeatItem)
        {
            string[] result = Split(strValue, strSplit);

            return ignoreRepeatItem ? DistinctStringArray(result) : result;
        }
        /// <summary>
        /// 采用递归将字符串分割成数组
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="strSplit">分割符</param>
        /// <param name="attachArray">string[]数组</param>
        /// <returns></returns>
        public static string[] Split(string strValue, string strSplit, string[] attachArray)
        {
            string[] strtmp = new string[attachArray.Length + 1];
            attachArray.CopyTo(strtmp, 0);

            int index = strValue.IndexOf(strSplit, 0);
            if (index < 0)
            {
                strtmp[attachArray.Length] = strValue;
                return strtmp;
            }
            else
            {
                strtmp[attachArray.Length] = strValue.Substring(0, index);
                return Split(strValue.Substring(index + strSplit.Length), strSplit, strtmp);
            }
        }
        /// <summary>
        /// 清除字符串数组中的重复项
        /// </summary>
        /// <param name="strArray">字符串数组</param>
        /// <param name="maxElementLength">字符串数组中单个元素的最大长度</param>
        /// <returns></returns>
        public static string[] DistinctStringArray(string[] strArray)
        {
            Hashtable h = new Hashtable();

            foreach (string s in strArray)
            {
                h[s.Trim()] = s;
            }

            string[] result = new string[h.Count];

            h.Keys.CopyTo(result, 0);

            return result;
        }
        #endregion

        #region 删除最后一个字符
        /// <summary>
        /// 删除最后一个字符
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string ClearLastChar(string strValue)
        {
            return (strValue == "") ? "" : strValue.Substring(0, strValue.Length - 1);
        }
        #endregion

        #region 格式化HTML,保留br,p,img
        /// <summary>
        /// 格式化HTML,保留br,p,img
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string FormatHTML(string strValue)
        {
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            return regEx.Replace(strValue, "");
        }
        #endregion

        #region 移除Html标记
        /// <summary>
        /// 移除Html标记
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string RemoveHtml(string strValue)
        {
            return Regex.Replace(strValue, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }
        #endregion

        #region 过滤HTML的不安全标签
        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string strValue)
        {
            strValue = Regex.Replace(strValue, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            strValue = Regex.Replace(strValue, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return strValue;
        }
        #endregion

        #region 替换回车换行符为html换行符
        /// <summary>
        /// 替换回车换行符为html换行符
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns></returns>
        public static string StrFormat(string strValue)
        {
            string str2;

            if (strValue == null)
            {
                str2 = "";
            }
            else
            {
                strValue = strValue.Replace("\r\n", "<br />");
                strValue = strValue.Replace("\n", "<br />");
                str2 = strValue;
            }
            return str2;
        }
        #endregion

        #endregion

        #region 数组操作

        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
        public static int InArrayIndex(string strValue, string[] stringArray, bool caseInsensetive)
        {
            for (int i = 0; i < stringArray.Length; i++)
            {
                if (caseInsensetive)
                {
                    if (strValue.ToLower() == stringArray[i].ToLower())
                        return i;
                }
                else if (strValue == stringArray[i])
                    return i;
            }
            return -1;
        }


        /// <summary>
        /// 判断指定字符串在指定字符串数组中的位置
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>		
        public static int InArrayIndex(string strValue, string[] stringArray)
        {
            return InArrayIndex(strValue, stringArray, true);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strValue, string[] stringArray, bool caseInsensetive)
        {
            return InArrayIndex(strValue, stringArray, caseInsensetive) >= 0;
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">字符串数组</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strValue, string[] stringArray)
        {
            return InArray(strValue, stringArray, false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">内部以逗号分割单词的字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strValue, string stringArray)
        {
            return InArray(strValue, Split(stringArray, ","), false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">内部以逗号分割单词的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strValue, string stringArray, string strSplit)
        {
            return InArray(strValue, Split(stringArray, strSplit), false);
        }

        /// <summary>
        /// 判断指定字符串是否属于指定字符串数组中的一个元素
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <param name="stringArray">内部以逗号分割单词的字符串</param>
        /// <param name="strSplit">分割字符串</param>
        /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
        /// <returns>判断结果</returns>
        public static bool InArray(string strValue, string stringArray, string strSplit, bool caseInsensetive)
        {
            return InArray(strValue, Split(stringArray, strSplit), caseInsensetive);
        }
        #endregion

        #region 日期时间操作

        /// <summary>
        /// 返回相差的秒数
        /// </summary>
        /// <param name="strValue">日期时间字符串</param>
        /// <param name="Sec">秒数</param>
        /// <returns></returns>
        public static int StrDateDiffSeconds(string strValue, int Sec)
        {
            TimeSpan ts = DateTime.Now - DateTime.Parse(strValue).AddSeconds(Sec);
            if (ts.TotalSeconds > int.MaxValue)
                return int.MaxValue;

            else if (ts.TotalSeconds < int.MinValue)
                return int.MinValue;

            return (int)ts.TotalSeconds;
        }
        /// <summary>
        /// 返回相差的分钟数
        /// </summary>
        /// <param name="strValue">日期时间字符串</param>
        /// <param name="Minutes">分钟数</param>
        /// <returns></returns>
        public static int StrDateDiffMinutes(string strValue, int Minutes)
        {
            if (strValue == "")
                return 1;

            TimeSpan ts = DateTime.Now - DateTime.Parse(strValue).AddMinutes(Minutes);
            if (ts.TotalMinutes > int.MaxValue)
                return int.MaxValue;
            else if (ts.TotalMinutes < int.MinValue)
                return int.MinValue;

            return (int)ts.TotalMinutes;
        }
        /// <summary>
        /// 返回相差的小时数
        /// </summary>
        /// <param name="strValue">日期时间字符串</param>
        /// <param name="Hours">小时数</param>
        /// <returns></returns>
        public static int StrDateDiffHours(string strValue, int Hours)
        {
            if (strValue=="")
                return 1;

            TimeSpan ts = DateTime.Now - DateTime.Parse(strValue).AddHours(Hours);
            if (ts.TotalHours > int.MaxValue)
                return int.MaxValue;
            else if (ts.TotalHours < int.MinValue)
                return int.MinValue;

            return (int)ts.TotalHours;
        }

        /// <summary>
        /// 返回相差的天数
        /// </summary>
        /// <param name="strValue">日期时间字符串</param>
        /// <param name="Days">天数</param>
        /// <returns></returns>
        public static int StrDateDiffDays(string strValue, int Days)
        {
            if (strValue == "")
                return 1;

            TimeSpan ts = DateTime.Now - DateTime.Parse(strValue).AddDays(Days);
            return (int)ts.TotalDays;
        }
        #endregion


        #region Cookie操作
        /// <summary>
        /// 获得cookie值
        /// </summary>
        /// <param name="CookieName">cookie名称</param>
        /// <param name="Key">cookie字键</param>
        /// <returns>值</returns>
        public static string GetCookie(string CookieName,string Key)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[CookieName] != null && HttpContext.Current.Request.Cookies[CookieName][Key] != null)
                return Utils.UrlDecode(HttpContext.Current.Request.Cookies[CookieName][Key].ToString());

            return "";
        }
        /// <summary>
        /// 获得cookie值
        /// </summary>
        /// <param name="CookieName">cookie名称</param>
        /// <returns>值</returns>
        public static string GetCookie(string CookieName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[CookieName] != null)
                return Utils.UrlDecode(HttpContext.Current.Request.Cookies[CookieName].ToString());

            return "";
        }
        /// <summary>
        /// 清空cookie
        /// </summary>
        /// <param name="cookieName">cookie名称</param>
        /// <param name="CookieDomain">cookie域</param>
        /// <returns>值</returns>
        public static void ClearCookie(string cookieName, string CookieDomain)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Values.Clear();
            cookie.Expires = DateTime.Now.AddYears(-1);
            cookie.Domain = CookieDomain;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        #endregion
    }
}
